import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login, register } from '@/api/auth'
import { ElMessage } from 'element-plus'
import router from '@/router'

export const useUserStore = defineStore('user', () => {
  const user = ref(null)
  const token = ref(null)

  const isAuthenticated = computed(() => !!token.value)

  // 登录
  async function userLogin(credentials) {
    try {
      const data = await login(credentials)
      console.log('[登录] 收到token:', data.access_token?.substring(0, 20) + '...')
      
      // 先保存所有数据到 localStorage
      localStorage.setItem('access_token', data.access_token)
      localStorage.setItem('refresh_token', data.refresh_token)
      console.log('[登录] Token已保存到localStorage')
      
      // 验证是否真的保存成功
      const savedToken = localStorage.getItem('access_token')
      console.log('[登录] 验证localStorage中的token:', savedToken?.substring(0, 20) + '...')
      
      // 保存用户信息（简化处理）
      const userData = { username: credentials.username }
      localStorage.setItem('user', JSON.stringify(userData))
      
      // 再更新 store
      token.value = data.access_token
      user.value = userData
      console.log('[登录] Store已更新, isAuthenticated:', !!token.value)
      
      // 显示成功消息
      ElMessage.success('登录成功')
      
      // 最后跳转到首页
      console.log('[登录] 准备跳转到首页')
      await router.push('/')
      console.log('[登录] 已跳转到首页')
    } catch (error) {
      console.error('[登录] 登录失败:', error)
      ElMessage.error('登录失败')
      throw error
    }
  }

  // 注册
  async function userRegister(userData) {
    try {
      await register(userData)
      ElMessage.success('注册成功，请登录')
      router.push('/login')
    } catch (error) {
      ElMessage.error('注册失败')
      throw error
    }
  }

  // 登出
  function logout() {
    user.value = null
    token.value = null
    localStorage.removeItem('access_token')
    localStorage.removeItem('refresh_token')
    localStorage.removeItem('user')
    router.push('/login')
    ElMessage.success('已退出登录')
  }

  // 恢复用户信息
  function restoreUser() {
    const storedToken = localStorage.getItem('access_token')
    const storedUser = localStorage.getItem('user')
    
    if (storedToken && storedUser) {
      token.value = storedToken
      user.value = JSON.parse(storedUser)
    }
  }

  return {
    user,
    token,
    isAuthenticated,
    userLogin,
    userRegister,
    logout,
    restoreUser
  }
})

